package com.tianzhu.service;

import java.time.Period;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tianzhu.domain.User;
import com.tianzhu.repositories.UserRepo;

@Service
@Transactional
@Slf4j
public class UserService {

   /* @Autowired
    private PasswordEncoder passwordEncoder;*/
    @Autowired
    private UserRepo userRepository;

    public User create(User user) {
        log.info("Creating {} user", user.getUsername());

        if (userRepository.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("Cannot create user with username  \"" + user.getUsername() + "\" , the username is already in use by another user.");
        }

        /*// Encode password
        user.setPassword(encryptPassword(user.getPassword()));
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);
        if (user.getAutomaticLogoutTime() == null) {
            user.setAutomaticLogoutTime(Period.hours(1));
        }*/

        // create entity
        return userRepository.save(user);
    }

   /* public User update(User user) {
        if (userRepository.findByIdNotAndUsername(user.getId(), user.getUsername()) != null) {
            throw new RuntimeException("Cannot update user with username  \"" + user.getUsername() + "\" , the username is already in use by another user.");
        }

        // save entity
        return userRepository.save(user);
    }*/

    public void delete(User user) {
        // delete entity
        userRepository.delete(user);
    }

    private String encryptPassword(String password) {
        //return passwordEncoder.encode(password);
    	return null;
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }
    
    @Cacheable("users")
    public User findByUsername(String username){
    	log.info("find user");
    	return userRepository.findByUsername(username);
    }
    
    
    @Cacheable("users")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        
        return user;
    }
}
